#define _CRT_SECURE_NO_WARNINGS 1

#include"List.h"

LTNode* ListInit(LTNode* phead)
{
	phead = (LTNode*)malloc(sizeof(LTNode));
	if (phead == NULL)
	{
		printf("ListPushBack:error!\n");
		exit(-1);
	}
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void ListPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* NewNode = (LTNode*)malloc(sizeof(LTNode));
	if (NewNode == NULL)
	{
		printf("ListPushBack:error!\n");
		exit(-1);
	}
	NewNode->data = x;
	phead->prev->next = NewNode;
	NewNode->prev = phead->prev;
	phead->prev = NewNode;
	NewNode->next = phead;
}

void ListPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* NewNode = (LTNode*)malloc(sizeof(LTNode));
	if (NewNode == NULL)
	{
		printf("ListPushFront:error!\n");
		exit(-1);
	}
	NewNode->data = x;
	NewNode->next = phead->next;
	NewNode->prev = phead;
	phead->next->prev = NewNode;
	phead->next = NewNode;
}

void ListInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	
	LTNode* NewNode = (LTNode*)malloc(sizeof(LTNode));
	if (NewNode == NULL)
	{
		printf("ListPushFront:error!\n");
		exit(-1);
	}
	NewNode->data = x;
	pos->prev->next = NewNode;
	NewNode->prev = pos->prev;
	pos->prev = NewNode;
	NewNode->next = pos;
}

void ListPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LTNode* aim = phead->prev;
	phead->prev = aim->prev;
	aim->prev->next = phead;
	free(aim);
}

void ListPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LTNode* aim = phead->next;
	phead->next = aim->next;
	aim->next->prev = phead;
	free(aim);
}

void ListErase(LTNode* pos)
{
	assert(pos);
	assert(pos->next != pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
}

LTNode* ListFind(LTNode* phead, LTDataType x)
{
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListPrint(LTNode* phead)
{
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
}

void ListDistroy(LTNode* phead)
{
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		cur = cur->next;
		free(cur->prev);
	}
	free(phead);
}